<template>
  <view class="material-selector-modal" v-if="visible" @click="handleMaskClick">
    <view class="selector-content" @click.stop>
      <view class="selector-header">
        <text class="selector-title">库存物资选择</text>
        <uni-icons type="close" size="20" color="#999" @click="handleClose"></uni-icons>
      </view>
      
      <view class="selector-body">
        <!-- 搜索条件 -->
        <view class="search-section">
          <view class="search-row">
            <!-- 当没有传入物料ID时，显示物料编码搜索 -->
            <input 
              class="search-input" 
              v-model="searchForm.itemCode"
              placeholder="请输入产品物料编码"
              v-if="!lineParams.itemId"
            />
            <input 
              class="search-input" 
              v-model="searchForm.batchCode"
              placeholder="请输入批次号"
            />
            <input 
              class="search-input" 
              v-model="searchForm.sn"
              placeholder="请输入SN"
            />
          </view>
          <view class="search-row">
            <!-- 当没有传入仓库ID时，显示仓库名称搜索 -->
            <input 
              class="search-input" 
              v-model="searchForm.warehouseName"
              placeholder="请输入仓库名称"
              v-if="!lineParams.warehouseId"
            />
            <input 
              class="search-input" 
              v-model="searchForm.locationName"
              placeholder="请输入库区名称"
            />
            <input 
              class="search-input" 
              v-model="searchForm.areaCode"
              placeholder="请输入库位编码"
            />
          </view>
          <view class="search-buttons">
            <button class="search-btn-primary" @click="handleSearch">
              <uni-icons type="search" size="16" color="#fff"></uni-icons>
              Q 搜索
            </button>
            <button class="search-btn-secondary" @click="handleReset">重置</button>
          </view>
        </view>
        
        <!-- 物料列表 -->
        <view class="material-list">
          <view class="list-header">
            <text class="list-title">库存物资列表</text>
            <text class="list-count">共 {{ total }} 条</text>
          </view>
          
          <view class="material-table">
            <view class="table-header">
              <view class="header-cell">选择</view>
              <!-- 当没有传入物料ID时，显示物料基础信息 -->
              <view class="header-cell" v-if="!lineParams.itemId">产品物料编码</view>
              <view class="header-cell" v-if="!lineParams.itemId">产品物料名称</view>
              <view class="header-cell" v-if="!lineParams.itemId">规格型号</view>
              <view class="header-cell" v-if="!lineParams.itemId">单位</view>
              <!-- 仓库相关信息始终显示 -->
              <view class="header-cell">仓库</view>
              <view class="header-cell">库区</view>
              <view class="header-cell">库位编码</view>
              <view class="header-cell">批次号</view>
              <view class="header-cell">SN</view>
              <view class="header-cell">在库数量</view>
            </view>
            
            <view 
              class="table-row" 
              v-for="material in materialList" 
              :key="material.materialStockId"
              @click="handleSelectMaterial(material)"
            >
              <view class="table-cell">
                <radio 
                  :checked="selectedMaterial && selectedMaterial.materialStockId === material.materialStockId"
                  @click.stop="handleSelectMaterial(material)"
                />
              </view>
              <!-- 当没有传入物料ID时，显示物料基础信息 -->
              <view class="table-cell" v-if="!lineParams.itemId">{{ material.itemCode }}</view>
              <view class="table-cell" v-if="!lineParams.itemId">{{ material.itemName }}</view>
              <view class="table-cell" v-if="!lineParams.itemId">{{ material.specification || '-' }}</view>
              <view class="table-cell" v-if="!lineParams.itemId">{{ material.unitName || material.unitOfMeasure || 'Pcs' }}</view>
              <!-- 仓库相关信息始终显示 -->
              <view class="table-cell">{{ material.warehouseName || '-' }}</view>
              <view class="table-cell">{{ material.locationName || '-' }}</view>
              <view class="table-cell">{{ material.areaCode || '-' }}</view>
              <view class="table-cell">{{ material.batchCode || '-' }}</view>
              <view class="table-cell">{{ material.sn || '-' }}</view>
              <view class="table-cell">{{ material.quantityOnhand }}</view>
            </view>
          </view>
          
          <!-- 分页 -->
          <view class="pagination" v-if="total > pageSize">
            <button 
              class="page-btn" 
              :disabled="pageNum <= 1"
              @click="handlePrevPage"
            >
              上一页
            </button>
            <text class="page-info">{{ pageNum }} / {{ Math.ceil(total / pageSize) }}</text>
            <button 
              class="page-btn" 
              :disabled="pageNum >= Math.ceil(total / pageSize)"
              @click="handleNextPage"
            >
              下一页
            </button>
          </view>
        </view>
      </view>
      
      <view class="selector-footer">
        <button class="footer-btn cancel-btn" @click="handleClose">取消</button>
        <button 
          class="footer-btn confirm-btn" 
          :disabled="!selectedMaterial"
          @click="handleConfirm"
        >
          确定
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { getMaterialStockList } from '@/api/wm/materialStock'

export default {
  name: 'MaterialSelector',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    // 行明细相关参数
    lineParams: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      materialList: [],
      selectedMaterial: null,
      total: 0,
      pageNum: 1,
      pageSize: 10,
      loading: false,
      searchForm: {
        itemCode: '',
        batchCode: '',
        sn: '',
        warehouseName: '',
        locationName: '',
        areaCode: ''
      }
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.initData()
        this.handleSearch()
      }
    }
  },
  methods: {
    // 初始化数据
    initData() {
      this.materialList = []
      this.selectedMaterial = null
      this.total = 0
      this.pageNum = 1
      this.resetSearchForm()
      
      // 根据行明细参数预设搜索条件
      if (this.lineParams.itemId) {
        this.searchForm.itemCode = this.lineParams.itemCode || ''
      }
      if (this.lineParams.warehouseId) {
        this.searchForm.warehouseName = this.lineParams.warehouseName || ''
      }
      if (this.lineParams.batchCode) {
        this.searchForm.batchCode = this.lineParams.batchCode || ''
      }
    },
    
    // 重置搜索表单
    resetSearchForm() {
      this.searchForm = {
        itemCode: '',
        batchCode: '',
        sn: '',
        warehouseName: '',
        locationName: '',
        areaCode: ''
      }
      
      // 重新应用父组件传入的预设值
      if (this.lineParams.itemId) {
        this.searchForm.itemCode = this.lineParams.itemCode || ''
      }
      if (this.lineParams.warehouseId) {
        this.searchForm.warehouseName = this.lineParams.warehouseName || ''
      }
      if (this.lineParams.batchCode) {
        this.searchForm.batchCode = this.lineParams.batchCode || ''
      }
    },
    
    // 搜索物料
    async handleSearch() {
      this.pageNum = 1
      await this.searchMaterials()
    },
    
    // 重置搜索
    handleReset() {
      this.resetSearchForm()
      this.handleSearch()
    },
    
    // 选择物料
    handleSelectMaterial(material) {
      this.selectedMaterial = material
    },
    
    // 上一页
    async handlePrevPage() {
      if (this.pageNum <= 1) return
      
      this.pageNum--
      await this.searchMaterials()
    },
    
    // 下一页
    async handleNextPage() {
      if (this.pageNum >= Math.ceil(this.total / this.pageSize)) return
      
      this.pageNum++
      await this.searchMaterials()
    },
    
    // 搜索物料（分离搜索逻辑）
    async searchMaterials() {
      try {
        this.loading = true
        
        const params = {
          ...this.searchForm,
          // 只查询可用且未冻结的库存
          stockStatus: 'AVAILABLE',
          frozenFlag: 'N',
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
        
        // 过滤空值
        Object.keys(params).forEach(key => {
          if (params[key] === '' || params[key] === null || params[key] === undefined) {
            delete params[key]
          }
        })
        
        const response = await getMaterialStockList(params)
        
        if (response && response.code === 200) {
          this.materialList = response.rows || []
          this.total = response.total || 0
        } else {
          uni.showToast({ 
            title: response.msg || '查询失败', 
            icon: 'none' 
          })
          this.materialList = []
          this.total = 0
        }
      } catch (error) {
        console.error('查询库存失败:', error)
        uni.showToast({ 
          title: '网络异常，请重试', 
          icon: 'none' 
        })
        this.materialList = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    
    // 确认选择
    handleConfirm() {
      if (!this.selectedMaterial) {
        uni.showToast({ title: '请选择物料', icon: 'none' })
        return
      }
      
      this.$emit('confirm', this.selectedMaterial)
      this.handleClose()
    },
    
    // 关闭选择器
    handleClose() {
      this.$emit('close')
    },
    
    // 点击遮罩关闭
    handleMaskClick() {
      this.handleClose()
    }
  }
}
</script>

<style lang="scss" scoped>
.material-selector-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1001;
  
  .selector-content {
    width: 95%;
    height: 90vh;
    margin: 5vh auto;
    background: #fff;
    border-radius: 16rpx;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  
  .selector-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx;
    border-bottom: 1rpx solid #eee;
    background: #f8f9fa;
    
    .selector-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .selector-body {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
  
  .selector-footer {
    display: flex;
    gap: 20rpx;
    padding: 30rpx;
    border-top: 1rpx solid #eee;
    background: #f8f9fa;
    
    .footer-btn {
      flex: 1;
      height: 70rpx;
      border-radius: 35rpx;
      border: none;
      font-size: 28rpx;
      font-weight: bold;
      
      &.cancel-btn {
        background: #f8f9fa;
        color: #666;
        border: 1rpx solid #ddd;
      }
      
      &.confirm-btn {
        background: linear-gradient(135deg, #007AFF 0%, #5AC8FA 100%);
        color: #fff;
        
        &:disabled {
          background: #ccc;
          color: #999;
        }
      }
    }
  }
}

.search-section {
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
  background: #f8f9fa;
  
  .search-row {
    display: flex;
    gap: 20rpx;
    margin-bottom: 20rpx;
    
    .search-input {
      flex: 1;
      height: 60rpx;
      padding: 0 15rpx;
      border: 1rpx solid #ddd;
      border-radius: 6rpx;
      font-size: 24rpx;
      
      &::placeholder {
        font-size: 22rpx;
        color: #999;
      }
      
    }
  }
  
  .search-buttons {
    display: flex;
    gap: 20rpx;
    
    .search-btn-primary {
      flex: 1;
      height: 60rpx;
      background: linear-gradient(135deg, #007AFF 0%, #5AC8FA 100%);
      color: #fff;
      border: none;
      border-radius: 6rpx;
      font-size: 26rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8rpx;
    }
    
    .search-btn-secondary {
      flex: 1;
      height: 60rpx;
      background: #f8f9fa;
      color: #666;
      border: 1rpx solid #ddd;
      border-radius: 6rpx;
      font-size: 26rpx;
    }
  }
}

.material-list {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  
  .list-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #eee;
    background: #f8f9fa;
    
    .list-title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
    }
    
    .list-count {
      font-size: 24rpx;
      color: #666;
    }
  }
  
  .material-table {
    flex: 1;
    overflow-y: auto;
    
    .table-header {
      display: flex;
      background: #f8f9fa;
      border-bottom: 1rpx solid #eee;
      position: sticky;
      top: 0;
      z-index: 10;
      
      .header-cell {
        padding: 15rpx 8rpx;
        font-size: 22rpx;
        font-weight: bold;
        color: #333;
        text-align: center;
        border-right: 1rpx solid #eee;
        flex: 1;
        min-width: 80rpx;
        
        &:nth-child(1) { 
          width: 60rpx; 
          flex: none;
        }
        &:last-child { 
          width: 80rpx; 
          flex: none;
        }
      }
    }
    
    .table-row {
      display: flex;
      border-bottom: 1rpx solid #eee;
      
      &:active {
        background: #f0f8ff;
      }
      
      .table-cell {
        padding: 15rpx 8rpx;
        font-size: 20rpx;
        color: #666;
        text-align: center;
        border-right: 1rpx solid #eee;
        display: flex;
        align-items: center;
        justify-content: center;
        flex: 1;
        min-width: 80rpx;
        word-break: break-all;
        
        &:nth-child(1) { 
          width: 60rpx; 
          flex: none;
        }
        &:last-child { 
          width: 80rpx; 
          flex: none;
          border-right: none;
        }
      }
    }
  }
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20rpx;
  padding: 20rpx;
  border-top: 1rpx solid #eee;
  background: #f8f9fa;
  
  .page-btn {
    padding: 10rpx 20rpx;
    border: 1rpx solid #ddd;
    border-radius: 6rpx;
    background: #fff;
    font-size: 24rpx;
    color: #666;
    
    &:disabled {
      background: #f5f5f5;
      color: #ccc;
    }
  }
  
  .page-info {
    font-size: 24rpx;
    color: #666;
  }
}
</style>
